package top.milkbox.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.milkbox.info.R;
import top.milkbox.service.PictureVerificationCodeService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/pictureVC")
public class PictureVerificationCodeController {

    @Autowired
    private PictureVerificationCodeService pvcService;

    // 生成图片验证码
    @GetMapping("/picture")
    public void getPicture(HttpSession session, HttpServletResponse response) {
        try {
            BufferedImage image = pvcService.initPictureCode(session);
            // 必须设置响应内容类型为图片，否则前台不识别
            response.setContentType("image/png");
            // 获取文件输出流
            OutputStream outputStream = response.getOutputStream();
            // 输出图片流
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 校验（仅测试）
//    @GetMapping("/check/{code}")
//    public R checkTest(
//            HttpSession session,
//            @PathVariable("code") String code
//    ) {
//        R r = new R();
//        Boolean isPass = pvcService.check(session, code);
//        r.setFlag(isPass);
//        if (isPass) {
//            r.setMessage("图片验证码(" + code + ")校验成功");
//        } else {
//            r.setMessage("图片验证码(" + code + ")校验失败");
//        }
//        return r;
//    }


}
